<template>
	<div class="form-item-radio">
		<van-field :name="itemKey" :label="label" :required="required" :disabled="disabled" :readonly="readonly">
			<template #input>
				<template v-if="!readonly">
					<van-radio-group :model-value="modelValue" direction="horizontal" @update:model-value="handleChange">
						<van-radio v-for="item in optionList" :key="item.value" :name="item.value" :disabled="disabled">
							{{ item.text }}
						</van-radio>
					</van-radio-group>
				</template>
				<template v-else>
					<div class="readonly-text">{{ currentText }}</div>
				</template>
			</template>
		</van-field>
	</div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { getDic } from '../../api/index'

export default {
	name: 'FormItemRadio',
	props: {
		required: {
			type: Boolean,
			default: false,
		},
		isView: {
			type: Boolean,
			default: false,
		},
		itemKey: {
			type: String,
			default: '',
		},
		modelValue: {
			type: String,
			default: '',
		},
		optionList: {
			type: Array,
			default: () => [],
		},
		label: {
			type: String,
			default: '',
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		readonly: {
			type: Boolean,
			default: false,
		},
		dicKey: {
			type: String,
			default: '',
		},
	},
	emits: ['update:modelValue', 'change'],
	setup(props, { emit }) {
		const optionList = ref([...props.optionList])

		// 初始化字典数据
		const initDic = async () => {
			if (!props.dicKey) return

			try {
				const data = await getDic(props.dicKey)
				console.log(`字典${props.dicKey}原始数据:`, data)

				optionList.value = data.map((item) => ({
					text: item.dictLabel, // 显示文本使用dictLabel
					value: item.dictValue, // 值使用dictValue
				}))
				//更新显示文本
				const target = optionList.value.find((o) => o.value === props.modelValue)
				currentText.value = target ? target.text : ''
			} catch (error) {
				console.error('获取字典数据失败:', error)
			}
		}

		// 处理值变化
		const handleChange = (value) => {
			console.log(`FormItemRadio[${props.itemKey}] 值变化:`, value)
			emit('update:modelValue', value)
			emit('change', { [props.itemKey]: value })
		}

		onMounted(() => {
			initDic()
		})

		const currentText = ref('')
		watch(
			() => props.modelValue,
			() => {
				const target = optionList.value.find((o) => o.value === props.modelValue)
				currentText.value = target ? target.text : ''
			},
			{ immediate: true }
		)
		return {
			optionList,
			handleChange,
			currentText,
		}
	},
}
</script>

<style lang="less" scoped>
.form-item-radio {
	:deep(.van-field__label) {
		width: 100px;
	}

	:deep(.van-radio-group) {
		.van-radio {
			margin-right: 20px;
		}
	}
}
</style>